package sfeir.gwt.ergosum.server;

import javax.servlet.ServletException;

import sfeir.gwt.ergosum.client.ClientApi;
import sfeir.gwt.ergosum.client.model.Person;
import sfeir.gwt.ergosum.server.guice.GuiceServletContextListener;
import sfeir.gwt.ergosum.server.service.ProfileService;
import sfeir.gwt.ergosum.server.service.ProfileServiceImpl;

import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;

@SuppressWarnings("serial")
@Singleton
public class ClientApiServiceImpl extends RemoteServiceServlet implements ClientApi {

    @Inject
    protected ProfileService profileService;

    @Override
    public void init() throws ServletException {
        Injector injector = (Injector) getServletContext().getAttribute(GuiceServletContextListener.INJECTOR_NAME);
        injector.injectMembers(this);
        // profileService = new ProfileServiceImpl();
    }

    @Override
    public Person getUserProfile() throws NotLoggedInException {
        return profileService.getUserProfile();
    }

    @Override
    public Long createProfile(Person p) throws NotLoggedInException {
        if (!UserServiceFactory.getUserService().isUserLoggedIn())
            throw new NotLoggedInException();
        return profileService.savePerson(p);
    }

    @Override
    public Person getProfile(String email) throws NotLoggedInException {
        return profileService.getProfile(email);
    }
    
    @Override
    public Boolean checkAlias(String alias) throws NotLoggedInException {
        return (profileService.getProfile(alias) == null);
    }

}
